import os
import subprocess
import threading

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, TextAreaField, FileField, IntegerField, RadioField, \
	SelectField
from wtforms.validators import DataRequired, Length


class LoginForm(FlaskForm):
	user_name = StringField(validators=[DataRequired("用户名不能为空"), Length(max=10, min=3, message="用户名长度大于3小于10")])
	password = PasswordField(validators=[DataRequired("密码不能为空"), Length(max=20, min=8, message="密码长度大于8小于20")])
	submit = SubmitField(label='提交')


class RegisterForm(LoginForm):
	submit = SubmitField(label='注册')


class GetAdminForm(FlaskForm):
	invite_code = StringField(validators=[DataRequired('邀请码不能为空'), Length(max=9, min=9, message="邀请码长度为9")])
	submit = SubmitField(label='提交')


class MakePostForm(FlaskForm):
	title = StringField(validators=[DataRequired('标题不能为空')])
	content = TextAreaField()
	submit = SubmitField(label='发布')


class MakeProblemForm(MakePostForm):
	time_limit = IntegerField(validators=[DataRequired('请填写时间限制')])
	memory_limit = IntegerField(validators=[DataRequired('请填写内存限制')])
	change_file = RadioField('更改数据文件', choices=[('Y', '更改'), ('N', '不更改')], default='N')
	file = FileField(name='file')


class SubmitForm(FlaskForm):
	code = TextAreaField(validators=[DataRequired()], render_kw={'rows': 40, 'cols': 100})
	language = SelectField(validators=[DataRequired()], choices=[('cpp', 'C++'), ('py', 'Python'), ('java', 'Java')],
						   default='cpp')
	submit = SubmitField('提交')


class Command(object):
	def __init__(self, cmd,name):
		self.cmd = cmd
		self.name=name
		self.process = None

	def run(self, timeout):
		def target():
			print('Thread started')
			self.process = subprocess.Popen(self.cmd, shell=True)
			self.process.communicate()
			print('Thread finished')

		thread = threading.Thread(target=target)
		thread.start()

		thread.join(timeout)
		if thread.is_alive():
			print('Terminating process')
			os.system('taskkill /f /pid %s' % self.name)
			thread.join()
